using System;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class CursorHelper : NodeHelper
    {
        public Camera camera;
        public Text text;
        public bool Hex;

        private void Update()
        {
            text.text = MathTools.ToVector2(GetPoint()).ToString();
        }

        private Vector3 GetPoint(float px, float py)
        {
            var r = camera.ScreenPointToRay(new Vector3(px, py, 0f));
            var p = UnityTools.RayToPlane(r.origin, r.direction, Vector3.up, new Vector3(r.origin.x, 0, r.origin.z));
            return p;
        }

        private Vector3Int GetPoint()
        {
            var p = GetPoint(Input.mousePosition.x, Input.mousePosition.y);
            return Hex ? MathTools.ToVector3(HexCube.FromPosition(p).ToOffset()) : ToVector3(p);
        }

        private Vector3Int ToVector3(Vector3 p)
        {
            return new Vector3Int((int)Math.Round(p.x, MidpointRounding.AwayFromZero), 0,
                (int)Math.Round(p.z, MidpointRounding.AwayFromZero));
        }
    }
}